package com.zhl.controller.login;

import com.zhl.controller.BaseServlet;
import com.zhl.model.User;
import com.zhl.service.UserService;
import com.zhl.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

@WebServlet("/login/*")
public class loginServlet extends BaseServlet {

    UserService userService = new UserServiceImpl();

    public void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String checkCode = req.getParameter("checkCode");
        Object sessionCode = req.getSession().getAttribute("sessionCode");
        User user = userService.findUserByName(username);
        String msg = "";
        if (checkCode.equals(sessionCode.toString())){
            if (user != null){
                if (password.equals(user.getPassword())){
                    msg = "登录成功";
                    Map<String, Object> user1 = userService.findUserAndDeptById(user.getId());
                    req.getSession().setAttribute("user",user1);
                    user.setLoginTime(new Date());
                    userService.updateUser(user,user.getId());
                    req.getSession().setAttribute("userById",user);
                }
                else {
                    msg = "密码错误";
                }
            }else {
                msg = "用户不存在";
            }
        }else {
            msg = "验证码错误";
        }
        resp.getWriter().write(msg);
    }

    public void logon(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{

        String email = req.getParameter("email");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        User user = new User();
        user.setEmail(email);
        user.setUsername(username);
        user.setPassword(password);
        boolean b = userService.saveUser(user);
        System.out.println(b);

    }
}
